//
//  WXGetTokenModle.m
//  MagicLampApp
//
//  Created by Zheng on 2019/2/18.
//  Copyright © 2019 zheng.magic.lamp.app. All rights reserved.
//

#import "WXGetTokenModle.h"
#import <WeexSDK/WeexSDK.h>
#import "MLAWebVC.h"

@interface WXGetTokenModle ()

@property (nonatomic, copy) WXModuleCallback photoAlbumCallback;

@end

@implementation WXGetTokenModle 

WX_EXPORT_METHOD(@selector(getUserInfo:))
WX_EXPORT_METHOD(@selector(openPhotoAlbum:))
WX_EXPORT_METHOD(@selector(getWebPay:));

- (void)getUserInfo:(WXModuleCallback)callback {
    callback(@{@"token":[CX_GetUserDefaults() objectForKey:kAccessToken]});
}

- (void)openPhotoAlbum:(WXModuleCallback)callback {
 
    _photoAlbumCallback = callback;
    
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:(id)self];
    imagePickerVC.allowCrop = YES;
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowPickingGif = NO;
    imagePickerVC.cropRect = CGRectMake(0, (CX_GetScreenHeight()-CX_GetScreenWidth())/2., CX_GetScreenWidth(), CX_GetScreenWidth()*0.74);
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagePickerVC animated:YES completion:nil];
    
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        UIImage *chooseImage = photos[0];
        [self uploadImage:chooseImage];
    }];

}

- (void)uploadImage:(UIImage *)image {
    NSData *fileData = UIImageJPEGRepresentation(image, 0.5);
    NSDictionary *params = @{@"file":fileData};
    
    [MLAHttpManage uploadHostType:MLAHttpHostType_Api api:kUploadFiles params:params success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        self.photoAlbumCallback(@{@"imgUrl":response[@"file_url"]});
    } failure:^{
        
    }];

}

- (void)getWebPay:(NSDictionary *)param {
    MLAWebVC *webVC = [[MLAWebVC alloc] init];
    webVC.urlStr = param[@"url"];
    webVC.title = param[@"title"];
    UINavigationController *navVC = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    [navVC pushViewController:webVC animated:YES];
}


@end
